package com.gdk.ksoft.assembly.utils.system;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;

import java.io.File;

/**
 * Created by hel on 2014-12-10.
 * 软件辅助类
 */
public class ApkUtils {

    /**
     * 重启应用
     */
    public static void restartApplication(Context context) {
        final Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
    }

    /**
     * 回到桌面
     */
    public static void backToDesktop(Context context){
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//加入flag
        intent.addCategory(Intent.CATEGORY_HOME);//回到的桌面的原理
        context.startActivity(intent);
    }

    /**
     * 获得版本号
     * @param context
     * @return
     */
    public static int getVersionCode(Context context){
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        }catch (Exception e){
            e.getMessage();
        }
        return  -1;
    }

    /**
     * 获得版本名
     * @param context
     * @return
     */
    public static String getVersionName(Context context){
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 安装APK文件
     * @param apkfile
     */
    public static void installApk(Context context,String apkfile)throws Exception{
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(apkfile)),"application/vnd.android.package-archive");
        context.startActivity(intent);
    }

}
